<template>
  <div class="buycar-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="searchObj" class="search-form" label-width="80px">
      <el-form-item label="用户ID">
        <el-input v-model="searchObj.user_id" placeholder="请输入用户ID" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="商品ID">
        <el-input v-model="searchObj.product_id" placeholder="请输入商品ID" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="searchObj.nums" placeholder="请输入数量" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮（已注释） -->
    <!-- <div class="operation-buttons">
      <el-button type="primary" @click="addWinVisible = true">
        <i class="el-icon-plus"></i> 新增购物车记录
      </el-button>
    </div> -->

    <!-- 表格区域 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%; margin-top: 15px;"
        v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="user_id" label="用户ID" width="120" align="center">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>user_id: {{ scope.row.user_id }}</div>
            </template>
            <template #reference>
              <el-tag type="info">{{ scope.row.user_id }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="用户" width="150" align="center">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>user: {{ users.find(u => u.id === scope.row.user_id)?.name }}</div>
            </template>
            <template #reference>
              <el-tag>{{ users.find(u => u.id === scope.row.user_id)?.name || '未知用户' }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="product_id" label="商品ID" width="120" align="center">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>product_id: {{ scope.row.product_id }}</div>
            </template>
            <template #reference>
              <el-tag type="info">{{ scope.row.product_id }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="商品" width="180" align="center">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>product: {{ products.find(p => p.id === scope.row.product_id)?.name }}</div>
            </template>
            <template #reference>
              <el-tag>{{ products.find(p => p.id === scope.row.product_id)?.name || '未知商品' }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="nums" label="数量" width="120" align="center" />
      <!-- 操作列（已注释） -->
      <!-- <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.$index, scope.row)"
          >
            <i class="el-icon-edit"></i> 编辑
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.$index, scope.row)"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right;"
    />

    <!-- 新增弹窗（已注释） -->
    <!-- <el-dialog
        title="新增购物车记录"
        v-model="addWinVisible"
        width="500px"
    >
      <el-form
          :model="obj"
          :rules="rules"
          ref="formRef"
          label-width="100px"
      >
        <el-form-item label="用户" prop="user_id">
          <el-select v-model="obj.user_id" placeholder="请选择用户" style="width: 240px">
            <el-option
                v-for="item in users"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
          <div style="margin-top:8px;color:#999">当前选择：{{ formUserName }}</div>
        </el-form-item>
        <el-form-item label="商品" prop="product_id">
          <el-select v-model="obj.product_id" placeholder="请选择商品" style="width: 240px">
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
          <div style="margin-top:8px;color:#999">当前选择：{{ formProductName }}</div>
        </el-form-item>
        <el-form-item label="数量" prop="nums">
          <el-input v-model="obj.nums" placeholder="请输入数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">确定</el-button>
      </template>
    </el-dialog> -->

    <!-- 编辑弹窗（已注释） -->
    <!-- <el-dialog
        title="编辑购物车记录"
        v-model="editWinVisible"
        width="500px"
    >
      <el-form
          :model="obj"
          :rules="rules"
          ref="formRef"
          label-width="100px"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="用户" prop="user_id">
          <el-select v-model="obj.user_id" placeholder="请选择用户" style="width: 240px">
            <el-option
                v-for="item in users"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
          <div style="margin-top:8px;color:#999">当前选择：{{ formUserName }}</div>
        </el-form-item>
        <el-form-item label="商品" prop="product_id">
          <el-select v-model="obj.product_id" placeholder="请选择商品" style="width: 240px">
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
          <div style="margin-top:8px;color:#999">当前选择：{{ formProductName }}</div>
        </el-form-item>
        <el-form-item label="数量" prop="nums">
          <el-input v-model="obj.nums" placeholder="请输入数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">确定</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import buycarAPI from '@/api/buycar_api.js';
import productAPI from '@/api/product_api.js';
import userAPI from '@/api/user_api.js';
import lodash from 'lodash';

// 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 搜索参数
const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  product_id: '',
  nums: ''
});

// 弹窗相关（已注释不需要的变量）
// const addWinVisible = ref(false);
// const editWinVisible = ref(false);
// const obj = ref({}); // 新增/编辑的数据对象
// const formRef = ref(null);

// 下拉数据源
const products = ref([]);
const users = ref([]);

// 表单验证规则（已注释）
// const rules = reactive({
//   user_id: [
//     { required: true, message: '请输入用户ID', trigger: 'blur' },
//     { type: 'number', message: '用户ID必须为数字', trigger: 'blur' }
//   ],
//   product_id: [
//     { required: true, message: '请输入商品ID', trigger: 'blur' },
//     { type: 'number', message: '商品ID必须为数字', trigger: 'blur' }
//   ],
//   nums: [
//     { required: true, message: '请输入数量', trigger: 'blur' }
//   ]
// });

// 表单显示的用户名称（已注释）
// const formUserName = computed(() => {
//   return users.value.find(item => item.id === obj.value.user_id)?.name || ''
// })

// 表单显示的商品名称（已注释）
// const formProductName = computed(() => {
//   return products.value.find(item => item.id === obj.value.product_id)?.name || ''
// })

// 查询列表数据
const search = async () => {
  loading.value = true;
  try {
    const result = await buycarAPI.page(searchObj.value);
    tableData.value = result.data;
    total.value = result.count;
  } catch (error) {
    ElMessage.error('获取数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 加载商品下拉
const loadProducts = async () => {
  try {
    const result = await productAPI.page({ current: 1, limit: 100 });
    products.value = result.data || [];
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    console.error(error);
  }
}

// 加载用户下拉
const loadUsers = async () => {
  try {
    const result = await userAPI.page({ current: 1, limit: 100 });
    users.value = result.data || [];
  } catch (error) {
    ElMessage.error('获取用户数据失败');
    console.error(error);
  }
}

// 页面加载时初始化数据
onMounted(async () => {
  await Promise.all([search(), loadProducts(), loadUsers()]);
});

// 分页大小改变
const handleSizeChange = () => {
  search();
};

// 当前页改变
const handleCurrentChange = () => {
  search();
};

// 搜索按钮点击
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await search();
};

// 重置搜索
const resetSearch = () => {
  searchObj.value = {
    current: 1,
    limit: 10,
    user_id: '',
    product_id: '',
    nums: ''
  };
  search();
};

// 编辑操作（已注释）
// const handleEdit = (index, row) => {
//   obj.value = lodash.clone(row);
//   editWinVisible.value = true;
// };

// 编辑提交（已注释）
// const editCommit = async () => {
//   await formRef.value.validate();
//   try {
//     await buycarAPI.edit(obj.value);
//     ElMessage.success('编辑成功');
//     editWinVisible.value = false;
//     await search();
//   } catch (error) {
//     ElMessage.error('编辑失败');
//     console.error(error);
//   }
// };

// 编辑取消（已注释）
// const editCancel = () => {
//   obj.value = {};
//   editWinVisible.value = false;
// };

// 新增提交（已注释）
// const addCommit = async () => {
//   await formRef.value.validate();
//   try {
//     await buycarAPI.add(obj.value);
//     ElMessage.success('新增成功');
//     addWinVisible.value = false;
//     obj.value = {};
//     await search();
//   } catch (error) {
//     ElMessage.error('新增失败');
//     console.error(error);
//   }
// };

// 新增取消（已注释）
// const addCancel = () => {
//   obj.value = {};
//   addWinVisible.value = false;
// };

// 删除操作（已注释）
// const handleDelete = (index, row) => {
//   ElMessageBox.confirm(
//       `确定要删除ID为${row.id}的记录吗？`,
//       '删除确认',
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//   ).then(async () => {
//     try {
//       await buycarAPI.del(row.id);
//       ElMessage.success('删除成功');
//       searchObj.value.current = 1;
//       await search();
//     } catch (error) {
//       ElMessage.error('删除失败');
//       console.error(error);
//     }
//   }).catch(() => {
//     // 取消删除
//   });
// };
</script>

<style scoped>
.buycar-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-form {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.operation-buttons {
  margin-bottom: 15px;
}
</style>